const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyParser = require('koa-bodyparser');
const logger = require('koa-logger');

const index = require('./routes/index');
const users = require('./routes/users');
const login = require('./routes/login');
const getxn = require('./routes/getxn');

const salesLead = require('./routes/salesLead');
const uapp = require('./routes/uapp');
const year = require('./routes/year');
const kehu = require('./routes/kehu');
const product = require('./routes/product'); //产品列表
const kpi = require('./routes/kpi'); //业绩目标
const client = require('./routes/client'); //客户
const ticket = require('./routes/ticket'); //全部工单
const tab = require('./routes/tab'); //系统公告

const duishou = require('./routes/duishou'); //
const guanhuai = require('./routes/guanhuai'); //
const qunfa = require('./routes/qunfa'); //
const shangji = require('./routes/shangji'); //
const xiaoxi = require('./routes/xiaoxi'); //
const yeji = require('./routes/yeji'); //

const db = require('./db');
const cors = require('@koa/cors');

// error handler
onerror(app);

db();
app.use(cors());

// middlewares
app.use(
  bodyParser({
    enableTypes: ['json', 'form', 'text'],
    multipart: true,
  })
);
app.use(json());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'));

app.use(
  views(__dirname + '/views', {
    extension: 'pug',
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());
app.use(login.routes(), login.allowedMethods());
app.use(salesLead.routes(), salesLead.allowedMethods());
app.use(uapp.routes(), uapp.allowedMethods());
app.use(year.routes(), year.allowedMethods());
app.use(kehu.routes(), kehu.allowedMethods());
app.use(product.routes(), product.allowedMethods());
app.use(kpi.routes(), kpi.allowedMethods());
app.use(client.routes(), client.allowedMethods());
app.use(ticket.routes(), ticket.allowedMethods()); //全部工单
app.use(tab.routes(), tab.allowedMethods()); //系统公告
app.use(getxn.routes(), getxn.allowedMethods());

app.use(duishou.routes(), duishou.allowedMethods());
app.use(guanhuai.routes(), guanhuai.allowedMethods());
app.use(qunfa.routes(), qunfa.allowedMethods());
app.use(shangji.routes(), shangji.allowedMethods());
app.use(xiaoxi.routes(), xiaoxi.allowedMethods());
app.use(yeji.routes(), yeji.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
});

module.exports = app;
